<template>
  <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="140px">
    <el-tabs type="border-card" v-model="activeName">
      <el-tab-pane :label="$t('product.product.base')" name="first">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item :label="t('product.product.name')" prop="name">
              <el-input v-model="ruleForm.name" />
            </el-form-item>

            <el-form-item :label="t('product.product.image_main')" prop="image_main">
              <Resources v-model="ruleForm.image_main" />
            </el-form-item>

            <el-form-item :label="t('product.product.image_slider')" prop="image_slider">
              <Resources v-model="ruleForm.image_slider" :number="10" />
            </el-form-item>

            <el-form-item :label="t('product.product.category_name')" prop="category_id">
              <SelectV3 v-model="ruleForm.category_id" :url="categoryList" />
            </el-form-item>

            <el-form-item :label="t('product.product.unit_name')" prop="unit_id">
              <SelectV3 v-model="ruleForm.unit_id" :url="unitList" />
            </el-form-item>

            <el-form-item :label="t('product.product.depository_name')" prop="depository_id">
              <SelectV3 v-model="ruleForm.depository_id" :url="depositoryList" />
            </el-form-item>

            <el-form-item :label="t('product.product.bar_code')" prop="bar_code">
              <el-input v-model="ruleForm.bar_code" />
            </el-form-item>

            <el-form-item :label="t('product.product.browse_false')" prop="browse_false">
              <el-input v-model="ruleForm.browse_false" />
            </el-form-item>

            <el-form-item :label="t('product.product.sales_false')" prop="sales_false">
              <el-input v-model="ruleForm.sales_false" />
            </el-form-item>

            <el-form-item :label="t('product.product.is_sales')" prop="is_sales">
              <el-radio-group v-model="ruleForm.is_sales">
                <el-radio :label="1">{{ $t("common.yes") }}</el-radio>
                <el-radio :label="0">{{ $t("common.no") }}</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item :label="t('product.product.is_postage')" prop="is_postage">
              <el-radio-group v-model="ruleForm.is_postage">
                <el-radio :label="1">{{ $t("common.yes") }}</el-radio>
                <el-radio :label="0">{{ $t("common.no") }}</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item :label="t('product.product.is_vip')" prop="is_vip">
              <el-radio-group v-model="ruleForm.is_vip">
                <el-radio :label="1">{{ $t("common.yes") }}</el-radio>
                <el-radio :label="0">{{ $t("common.no") }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-form-item :label="t('product.product.status')" prop="status">
            <el-radio-group v-model="ruleForm.status">
              <el-radio :label="10">{{ $t("product.product.ground") }}</el-radio>
              <el-radio :label="20">{{ $t("product.product.shelf") }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
      </el-tab-pane>
      <el-tab-pane :label="$t('product.product.spec')" name="second">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-col :span="24">
              <el-form-item :label="t('product.product.spec_type')" prop="spec_type">
                <el-radio-group v-model="ruleForm.spec_type">
                  <el-radio :label="0">{{ $t("product.product.single_spec") }}</el-radio>
                  <el-radio :label="1">{{ $t("product.product.multiple_spec") }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-col>

          <el-col :span="24" v-if="ruleForm.spec_type === 0">
            <el-col :span="24">
              <el-table :data="stockSingle" border>
                <el-table-column :label="$t('product.product.image')" align="center">
                  <template #default="scope">
                    <Resources v-model="scope.row.image" />
                  </template>
                </el-table-column>
                <el-table-column prop="price" :label="$t('product.product.price')" align="center">
                  <template #default="scope">
                    <el-input v-model="scope.row.price" />
                  </template>
                </el-table-column>
                <el-table-column prop="price_vip" :label="$t('product.product.price_vip')" align="center">
                  <template #default="scope">
                    <el-input v-model="scope.row.price_vip" />
                  </template>
                </el-table-column>
                <el-table-column prop="price_cost" :label="$t('product.product.price_cost')" align="center">
                  <template #default="scope">
                    <el-input v-model="scope.row.price_cost" />
                  </template>
                </el-table-column>
                <el-table-column prop="bar_code" :label="$t('product.product.bar_code')" align="center">
                  <template #default="scope">
                    <el-input v-model="scope.row.bar_code" />
                  </template>
                </el-table-column>
                <el-table-column prop="stock" :label="$t('product.product.stock')" align="center">
                  <template #default="scope">
                    <el-input v-model="scope.row.stock" />
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-col>

          <el-col :span="24" v-else>
            <el-col :span="24">
              <el-table :data="specs" border :empty-text="t('product.product.emptyAddSpec')">
                <el-table-column :label="$t('product.product.spec_name')" align="center" width="400px;">
                  <template #header>
                    {{ t("product.product.spec_name") }}
                    <el-button type="primary" circle :icon="Plus" @click="addSpec" />
                    <el-button type="success" @click="generate" :disabled="specs.length == 0">{{
                      $t("product.product.generate")
                    }}</el-button>
                  </template>
                  <template #default="scope">
                    <el-input v-model="scope.row.name" />
                  </template>
                </el-table-column>

                <el-table-column :label="$t('product.product.spec_value')" align="center">
                  <template #default="scope">
                    <el-tag
                      v-for="value in scope.row.value"
                      :key="value"
                      class="mx-1"
                      closable
                      :disable-transitions="false"
                      @close="handleRemove(value, scope)"
                    >
                      {{ value }}
                    </el-tag>
                  </template>
                </el-table-column>

                <el-table-column :label="$t('common.operation')" align="center" width="220px;">
                  <template #default="scope">
                    <el-input
                      v-if="scope.row.input"
                      v-model="inputValue"
                      class="mx-1"
                      :ref="setItemRef"
                      @keyup.enter="handleInputConfirm(scope)"
                      @blur="handleInputConfirm(scope)"
                    />
                    <view v-else>
                      <el-button class="button-new-tag ml-1" @click="showInput(scope)">
                        {{ $t("product.product.addSpecValue") }}
                      </el-button>
                      <el-button type="danger" :icon="Delete" circle @click="removeAttr(scope)" />
                    </view>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
            <br />
            <el-col :span="24">
              <el-table :data="stockMultiple" border stripe>
                <el-table-column :label="$t('product.product.suk')" align="center">
                  <template #default="scope">
                    {{ scope.row.suk }}
                  </template>
                </el-table-column>
                <el-table-column :label="$t('product.product.image')" align="center">
                  <template #default="scope">
                    <Resources v-model="scope.row.image" />
                  </template>
                </el-table-column>

                <el-table-column prop="price" :label="$t('product.product.price')" align="center">
                  <template #default="scope">
                    <el-input v-model="scope.row.price" />
                  </template>
                </el-table-column>

                <el-table-column prop="price_vip" :label="$t('product.product.price_vip')" align="center">
                  <template #default="scope">
                    <el-input v-model="scope.row.price_vip" />
                  </template>
                </el-table-column>

                <el-table-column prop="price_cost" :label="$t('product.product.price_cost')" align="center">
                  <template #default="scope">
                    <el-input v-model="scope.row.price_cost" />
                  </template>
                </el-table-column>

                <el-table-column prop="bar_code" :label="$t('product.product.bar_code')" align="center">
                  <template #default="scope">
                    <el-input v-model="scope.row.bar_code" />
                  </template>
                </el-table-column>

                <el-table-column prop="stock" :label="$t('product.product.stock')" align="center">
                  <template #default="scope">
                    <el-input v-model="scope.row.stock" />
                  </template>
                </el-table-column>

                <el-table-column :label="$t('common.operation')" align="center" width="400px;">
                  <template #header>
                    <el-checkbox-group v-model="checkedFields">
                      <el-checkbox v-for="label in fields" :key="label" :label="label">{{
                        t("product.product." + label)
                      }}</el-checkbox>
                    </el-checkbox-group>
                  </template>
                  <template #default="scope">
                    <el-button type="success" @click="sync(scope.row)">{{ t("product.product.sync") }}</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane :label="$t('product.product.detail')" name="third">
        <el-form-item :label="t('product.product.info')" prop="info">
          <WangEditor v-model:value="ruleForm.info" />
        </el-form-item>
      </el-tab-pane>
      <br />
      <el-row :gutter="20">
        <el-col :span="8"></el-col>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">{{ t("common.save") }}</el-button>
          <el-button type="danger" @click="next(ruleFormRef)" v-show="activeName != 'third'">{{ t("common.next") }}</el-button>
          <el-button type="warning" @click="back(ruleFormRef)" v-show="activeName != 'first'">{{ t("common.back") }}</el-button>
        </el-form-item>
      </el-row>
    </el-tabs>
  </el-form>
</template>
<script lang="ts" setup>
import { reactive, ref } from "vue";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { useRoute } from "vue-router";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";
import { Delete, Plus } from "@element-plus/icons-vue";
import { productCreate as create, depositoryList, categoryList } from "@/api/modules/product";
import { unitList } from "@/api/modules/common";
import WangEditor from "@/components/WangEditor/index.vue";

import Resources from "@/components/Resources/index.vue";
import SelectV3 from "@/components/SelectV3/index.vue";

const route = useRoute();
const { t } = useI18n();

const activeName = ref("first");

const ruleForm = reactive({
  name: "",
  image_main: "",
  info: "",
  bar_code: "",
  image_slider: "",
  browse_false: 0,
  sales_false: 0,
  is_sales: 0,
  is_postage: 0,
  is_vip: 0,
  spec_type: 0,
  unit_id: 0,
  category_id: 0,
  depository_id: 0,
  status: 10,
  specs: [],
  stocks: []
});

const tabStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();
const rules = reactive<FormRules>({
  name: [{ required: true, message: t("product.product.rule.name"), trigger: "blur" }],
  image_main: [{ required: true, message: t("product.product.rule.image_main"), trigger: "blur" }],
  info: [{ required: true, message: t("product.product.rule.info"), trigger: "blur" }],
  category_id: [{ required: true, message: t("product.product.rule.category_name"), trigger: "blur" }]
});

const ruleFormRef = ref<FormInstance>();
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(valid => {
    if (valid && mergeForm()) {
      const action = create;
      action(ruleForm).then(response => {
        ElMessage.success(response.message);
        setTimeout(() => {
          if (route.meta.isAffix) return;
          tabStore.removeTabs(route.fullPath);
          keepAliveStore.removeKeepAliveName(route.name as string);
        }, 200);
      });
    } else {
      ElMessage.error("请根据提示输入信息！");
    }
  });
};

const stockSingle = reactive([{ image: "", price: 0, price_vip: 0, price_cost: 0, bar_code: "", stock: 0 }]);
const stockMultiple = ref([]);
const specs = reactive([]);
const inputValue = ref("");
const addSpec = () => {
  if (checkSpec() == false) {
    return;
  }

  specs.push({
    name: "",
    value: [],
    input: false
  });
};

const checkSpec = () => {
  for (let index in specs) {
    const item = specs[index];
    if (!item.name) {
      ElMessage.error(t("product.product.rule.spec_name"));
      return false;
    }

    if (item.value.length == 0) {
      ElMessage.error(t("product.product.rule.spec_value"));
      return false;
    }
  }

  return true;
};

const handleInputConfirm = scope => {
  if (inputValue.value && scope.row.value.indexOf(inputValue.value) < 0) {
    scope.row.value.push(inputValue.value);
  }

  scope.row.input = false;
  inputValue.value = "";
};

const showInput = scope => {
  specs.forEach(spec => {
    spec.input = false;
  });

  scope.row.input = true;
};
const handleRemove = (tag: string, scope) => {
  scope.row.value.splice(scope.row.value.indexOf(tag), 1);
};
const removeAttr = scope => {
  specs.splice(scope.$index);
};

const setItemRef = el => {
  try {
    if (el) el!.focus();
  } catch (error) {}
};

const next = (formEl: FormInstance | undefined) => {
  if (formEl) {
    formEl.validate(() => {});
  }

  switch (activeName.value) {
    case "first":
      activeName.value = "second";
      break;
    case "second":
      activeName.value = "third";
      break;
  }
};

const back = (formEl: FormInstance | undefined) => {
  if (formEl) {
    formEl.validate(() => {});
  }

  switch (activeName.value) {
    case "second":
      activeName.value = "first";
      break;
    case "third":
      activeName.value = "second";
      break;
  }
};

const mergeForm = () => {
  ruleForm.specs = [];
  ruleForm.stocks = [];
  if (ruleForm.spec_type == 1) {
    if (checkSpec() === false) {
      return false;
    }

    specs.forEach(spec => {
      ruleForm.specs.push({
        name: spec.name,
        value: spec.value.join(",")
      });
    });

    ruleForm.stocks = stockMultiple;
  } else {
    ruleForm.stocks.push(stockSingle[0]);
  }

  return true;
};

const generate = () => {
  if (checkSpec() === false) {
    return false;
  }

  const suks = generateOldStockMultiple();
  const data = generateStocks(generateAttrs());

  data.forEach(item => {
    const suk = Array.isArray(item) ? item.join(",") : item;
    const spec = suks[suk] ? suks[suk] : { image: "", price: 0, price_vip: 0, price_cost: 0, bar_code: "", stock: 0 };
    spec.suk = suk;

    stockMultiple.value.push(spec);
  });
};

const generateOldStockMultiple = () => {
  const data = {};
  stockMultiple.value.forEach(stock => {
    const suk = stock.suk;
    data[suk] = stock;
  });

  stockMultiple.value = [];
  return data;
};

const generateAttrs = () => {
  const attrs = [];
  specs.forEach(spec => {
    attrs.push(spec.value);
  });

  return attrs;
};

const generateStocks = attrs => {
  let data = attrs.shift();
  let shifted;
  while ((shifted = attrs.shift())) {
    let base = data;
    data = [];
    base.forEach(content => {
      content = Array.isArray(content) ? content : [content];
      shifted.forEach(value => {
        value = Array.isArray(value) ? value : [value];
        data.push([...content, ...value].sort());
      });
    });
  }

  return data;
};

const fields = ["image", "price", "price_vip", "price_cost", "bar_code", "stock"];
const checkedFields = ref(["image", "price", "price_vip", "price_cost", "bar_code", "stock"]);
const sync = row => {
  stockMultiple.value.forEach(stock => {
    checkedFields.value.forEach(field => {
      stock[field] = row[field];
    });
    // stock.image = row.image;
    // stock.price = row.price;
    // stock.price_vip = row.price_vip;
    // stock.price_cost = row.price_cost;
    // stock.bar_code = row.bar_code;
    // stock.stock = row.stock;
  });
};
</script>
